package com.lanxin.xxform.services.impls;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.lanxin.xxform.aspects.exceptions.ServiceException;
import com.lanxin.xxform.beans.User;
import com.lanxin.xxform.mappers.UserMapper;
import com.lanxin.xxform.services.UserService;
import com.lanxin.xxform.tools.JetCriteria;
import com.lanxin.xxform.tools.JetDate;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    private boolean exist(String account) {
        JetCriteria criteria = new JetCriteria();
        criteria.add("account", account);
        if (userMapper.count(criteria) > 0) {
            return true;
        }
        return false;
    }

    @Override
    public int register(String account, String password, String ip) {
        if (exist(account)) {
            throw new ServiceException("账户已存在");
        }
        User user = new User();
        user.setAccount(account);
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        user.setCreateTime(JetDate.timeNow());
        user.setIp(ip);
        user.setStatus(1);
        return userMapper.insert(user);
    }

    @Override
    public User login(String account, String password, String ip) {
        if (! exist(account)) {
            throw new ServiceException("账户不存在");
        }
        JetCriteria criteria = new JetCriteria();
        criteria.add("account", account);
        criteria.add("password", DigestUtils.md5DigestAsHex(password.getBytes()));
        for (User user : userMapper.findAll(criteria)) {
            return user;
        }
        return null;
    }

    @Override
    public User get(long id) {
        User user = userMapper.find(id);
        if (user == null) {
            throw new ServiceException("用户信息不存在");
        }
        return user;
    }

    @Override
    public int setInfo(User user) {
        User o = get(user.getId());
        if (o != null) {
            o.setName(user.getName());
            return userMapper.update(user);
        }
        return 0;
    }
    
}
